#!/usr/bin/env bash
set -euo pipefail

# bootstrap_dev.sh
# macOS (Apple Silicon) friendly dev bootstrap
# - Prefer `uv init --python=3.11` / `uv add` if available
# - Fallback to python -m venv and pip install
# - Use Aliyun PyPI mirror for faster installs in China
# - Verify virtualenv and a few core packages are importable and print versions

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$REPO_ROOT"

PYTHON_PREF="python3.11"
PYTHON=""

echo "[bootstrap] 检查系统信息..."
uname_s=$(uname -s)
uname_m=$(uname -m)
echo "[bootstrap] Host: $uname_s $uname_m"

# find a python executable
if command -v $PYTHON_PREF >/dev/null 2>&1; then
  PYTHON=$PYTHON_PREF
elif command -v python3 >/dev/null 2>&1; then
  PYTHON=python3
elif command -v python >/dev/null 2>&1; then
  PYTHON=python
else
  echo "未找到可用的 Python，请先安装 Python 3.11 或 3.x" >&2
  exit 1
fi

echo "[bootstrap] 使用 Python: $($PYTHON --version 2>&1)"

VENV_DIR=".venv"

use_uv=false
if command -v uv >/dev/null 2>&1; then
  echo "[bootstrap] 检测到 'uv' 工具，优先使用 uv 来创建/管理虚拟环境"
  # 首先尝试 uv sync（如果你使用 uv 的 lock/lockfile workflow，这将同步环境并安装依赖）
  echo "[bootstrap] 尝试运行: uv sync"
  if uv sync; then
    echo "[bootstrap] uv sync 成功：虚拟环境与依赖已同步，完成。"
    exit 0
  else
    echo "[bootstrap] uv sync 未成功，继续尝试使用 uv init 或回退到 venv" >&2
    use_uv=true
  fi
fi

REQUIREMENTS_FILE="requirements.txt"
if [[ ! -f "$REQUIREMENTS_FILE" ]]; then
  echo "[bootstrap] 警告：未找到 $REQUIREMENTS_FILE，后续安装会被跳过。" >&2
fi

PYPI_MIRROR="https://mirrors.aliyun.com/pypi/simple"

if $use_uv; then
  echo "[bootstrap] 运行: uv init --python=3.11"
  if uv init --python=3.11 "$VENV_DIR"; then
    echo "[bootstrap] uv init 完成"
  else
    echo "[bootstrap] uv init 失败，退回到 venv 方法" >&2
    use_uv=false
  fi
fi

if $use_uv && [[ -f "$REQUIREMENTS_FILE" ]]; then
  echo "[bootstrap] 使用 uv add 从阿里云镜像安装 requirements.txt"
  # try with explicit index url if uv supports it
  if uv add -r "$REQUIREMENTS_FILE" --index-url "$PYPI_MIRROR"; then
    echo "[bootstrap] uv add 完成"
  else
    echo "[bootstrap] uv add 带镜像参数失败，尝试不带镜像参数安装" >&2
    if uv add -r "$REQUIREMENTS_FILE"; then
      echo "[bootstrap] uv add 完成（不带镜像参数）"
    else
      echo "[bootstrap] uv add 安装失败，退回到 venv+pip 安装" >&2
      use_uv=false
    fi
  fi
fi

if ! $use_uv; then
  echo "[bootstrap] 使用 python -m venv 创建虚拟环境: $VENV_DIR"
  $PYTHON -m venv "$VENV_DIR"
  echo "[bootstrap] 激活虚拟环境并升级 pip"
  # shellcheck disable=SC1091
  source "$VENV_DIR/bin/activate"
  python -m pip install --upgrade pip setuptools wheel
  if [[ -f "$REQUIREMENTS_FILE" ]]; then
    echo "[bootstrap] 使用阿里云镜像安装依赖：pip install -r $REQUIREMENTS_FILE"
    pip install -r "$REQUIREMENTS_FILE" -i "$PYPI_MIRROR"
  fi
fi

echo "[bootstrap] 验证虚拟环境和关键依赖"
VENV_PY="$VENV_DIR/bin/python"
if [[ ! -x "$VENV_PY" ]]; then
  # try to detect uv-created env python
  if [[ -d "$VENV_DIR" ]]; then
    if [[ -x "$VENV_DIR/bin/python" ]]; then
      VENV_PY="$VENV_DIR/bin/python"
    else
      VENV_PY="$PYTHON"
    fi
  else
    VENV_PY="$PYTHON"
  fi
fi

echo "[bootstrap] 使用解释器: $($VENV_PY --version 2>&1)"

echo "[bootstrap] 检查核心包是否可导入及版本：rich, matplotlib, numpy"
"$VENV_PY" - <<'PY'
import importlib, sys
pkgs = ['rich','matplotlib','numpy']
for p in pkgs:
    try:
        m = importlib.import_module(p)
        ver = getattr(m, '__version__', 'unknown')
        print(f'{p}: OK, version={ver}')
    except Exception as e:
        print(f'{p}: MISSING ({e})')
sys.exit(0)
PY

echo "[bootstrap] 完成：虚拟环境路径 => $(realpath "$VENV_DIR")"
echo "[bootstrap] 要在该环境里运行脚本，请使用：source $VENV_DIR/bin/activate 或 $VENV_DIR/bin/python script.py"

exit 0
